import React, { Component } from 'react';
import { Checkbox, Alert } from 'antd';
import { connect } from 'dva';
import Link from 'umi/link';
import Login from '@/components/Login';
import styles from './Login.less';

const { UserName, Password, Submit } = Login;

@connect(({ session, loading }) => ({
    session,
    submitting: loading.effects['session/login'],
}))

class LoginPage extends Component {
    state = {
        autoLogin: true,
    };

    handleSubmit = (err, values) => {
        if (!err) {
            this.props.dispatch({
                type: 'session/login',
                params: values
            });
        }
    };

    changeAutoLogin = e => {
        this.setState({
            autoLogin: e.target.checked,
        });
    };

    renderMessage = content => (
        <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
    );

    render() {
        const { session, submitting } = this.props;
        return (
            <div className={styles.main}>
                <div style={{textAlign: "center", marginTop: 70, marginBottom: 50}}>
                    <h1>{window.GLOBAL.PROJECT_NAME}</h1>
                </div>
                <Login onSubmit={this.handleSubmit} ref={form => { this.loginForm = form; }}>
                    {session.status === "error" && !submitting && this.renderMessage('账户或密码错误')}
                    <UserName name="username" placeholder={"用户名"}
                        rules={[{
                                required: true,
                                message: '请输入用户名!',
                            },
                        ]}
                    />
                    <Password name="password" placeholder={"密码"}
                        rules={[{
                                required: true,
                                message: '请输入密码！',
                            },
                        ]}
                        onPressEnter={e => {
                            e.preventDefault();
                            this.loginForm.validateFields(this.handleSubmit);
                        }}
                    />
                    <div>
                        <Checkbox checked={this.state.autoLogin} onChange={this.changeAutoLogin}>自动登录</Checkbox>
                        <a style={{ float: 'right' }} href="/user">忘记密码</a>
                    </div>
                    <Submit loading={submitting}>登录</Submit>
                    <div className={styles.other}>
                        <Link className={styles.register} to="/user/register">注册账户</Link>
                    </div>
                </Login>
            </div>
        );
    }
}

export default LoginPage;
